package testJdk.base.juc_test.fork_and_join;

import org.junit.Test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @ClassName : learn_jdk.base.juc_test.fork_and_join.TestForkJoinPool
 * @Description : 类描述
 * Created by cyd on 2021-10-25 14:26:27
 */
public class TestForkJoinPool {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinSumCalculate task = new ForkJoinSumCalculate(0L, 100000000000L);
        Long result = forkJoinPool.invoke(task);
        System.out.println(result);
        long endTime = System.currentTimeMillis();
        System.out.println("耗时:" + (endTime - startTime));// 1049,6817
    }

    @Test
    public void test() {
        long startTime = System.currentTimeMillis();

        long sum = 0L;
        for (long i = 0L; i < 100000000000L; i++) {
            sum += i;
        }
        System.out.println(sum);
        long endTime = System.currentTimeMillis();
        System.out.println("耗时:" + (endTime - startTime));// 2372,23684
    }
}

class ForkJoinSumCalculate extends RecursiveTask<Long> {

    private long start;
    private long end;

    // 临界值
    private static final long THRESHOLD = 1000L;

    public ForkJoinSumCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        // 判断是否到达临界值
        long length = end - start;
        if (length <= THRESHOLD) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end) / 2;

            ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
            left.fork();

            ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle + 1, end);
            right.fork();

            return left.join() + right.join();
        }
    }
}
